package com.varton.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
 *
 * @author varton
 */
public class BeanUtil {
    public static <S,T> List<T> copyedModelList(List<S> sourceList, Class<T> targetClass) {
        if (sourceList != null){
            try {
                List<T> targetList = new ArrayList<>(sourceList.size());
                for (S s : sourceList){
                    T t = copyProperties(s, targetClass);
                    targetList.add(t);
                }
                return targetList;
            }catch (Exception e){

            }
        }
        return null;
    }

    public static <T, S> T copyProperties(S source, Class<T> targetClass) {
        if (source != null){
            try {
                T t = targetClass.newInstance();
                copyProperties(source,t);
                return t;
            }catch (Exception e){

            }
        }
        return null;
    }

    public static <S, T> void copyProperties(S source, T t) {
        Field[] targetFields = t.getClass().getDeclaredFields();
        for (Field targetField : targetFields) {
            try {
                Field sourceField = source.getClass().getDeclaredField(targetField.getName());
                sourceField.setAccessible(true);
                Object val = sourceField.get(source);

                targetField.setAccessible(true);
                targetField.set(t, val);
            } catch (IllegalAccessException e) {
            } catch (NoSuchFieldException e) {
            }

        }
    }
}